<?php

namespace app\apiadmin\service\TCSS;

use TencentCloud\Common\Credential;
use TencentCloud\Live\V20180801\LiveClient;
use TencentCloud\Live\V20180801\Models\CreateLivePullStreamTaskRequest;
use TencentCloud\Live\V20180801\Models\CreateRecordTaskRequest;
use TencentCloud\Live\V20180801\Models\DeleteLivePullStreamTaskRequest;
use TencentCloud\Live\V20180801\Models\DeleteRecordTaskRequest;
use TencentCloud\Live\V20180801\Models\DescribeLiveDomainRequest;
use TencentCloud\Live\V20180801\Models\DescribeLivePullStreamTasksRequest;
use TencentCloud\Live\V20180801\Models\DescribeLivePullStreamTaskStatusRequest;
use TencentCloud\Live\V20180801\Models\DescribeRecordTaskRequest;
use TencentCloud\Live\V20180801\Models\ModifyLivePullStreamTaskRequest;

/**
 * 腾讯 css 直播业务封装类
 */
class TCSSService
{

    private $_liveClient;
    private $_play_domain;
    private $_play_key_1;
    private $_play_key_2;

    private $_push_domain;
    private $_push_key_1;
    private $_push_key_2;
    private $_callback_url;

    private $cred;

    /**
     * 直播管理
     */
    public function __construct($config = [])
    {

        $id = env("Tencent.TENCENTCLOUD_SECRET_ID");
        $key = env("Tencent.TENCENTCLOUD_SECRET_KEY");
        $this->_play_domain = env("Tencent.PlayDomain");
        $this->_play_key_1 = env("Tencent.live_play_key_1");
        $this->_play_key_2 = env("Tencent.live_play_key_2");

        $this->_push_domain = env("Tencent.PushDomain");
        $this->_push_key_1 = env("Tencent.live_push_key_1");
        $this->_push_key_2 = env("Tencent.live_push_key_2");

        $this->_callback_url = env("Tencent.live_push_callback_url");

        $cred = new Credential($id, $key);
        $this->cred = $cred;

        $this->_liveClient = new LiveClient($cred, "ap-beijing");

    }
    public function getUrlInfo()
    {
        $req = new DescribeLiveDomainRequest();
        $req->DomainName = $this->_play_domain;
        $info_1 = $this->_liveClient->DescribeLiveDomain($req);

        $req = new DescribeLiveDomainRequest();
        $req->DomainName = $this->_push_domain;
        $info_2 = $this->_liveClient->DescribeLiveDomain($req);
        return [
            "domain_play_info" => $info_1,
            "domain_push_info" => $info_2,
        ];

    }

    /**
     * 获取推流地址
     * 如果不传key和过期时间，将返回不含防盗链的url
     * @param string domain 您用来推流的域名
     *        streamName 您用来区别不同推流地址的唯一流名称
     *        time 过期时间 sample 2016-11-12 12:00:00
     * @return  string url
     */
    function getPushUrl($streamName, $time, $appName = "live")
    {
        if ($this->_push_key_1 && $time && !empty($streamName)) {
            $txTime = strtoupper(base_convert(strtotime($time), 10, 16));
            //txSecret = MD5( KEY + streamName + txTime )
            $txSecret = md5($this->_push_key_1 . $streamName . $txTime);
            $ext_str = "?" . http_build_query(array(
                "txSecret" => $txSecret,
                "txTime" => $txTime,
            ));
        }

        return "rtmp://" . $this->_push_domain . "/" . $appName . "/" . $streamName . (isset($ext_str) ? $ext_str : "");

    }

    function getPlayUrl($streamName, $time, $appName = "live")
    {
        if ($this->_play_key_1 && $time && !empty($streamName)) {
            $txTime = strtoupper(base_convert(strtotime($time), 10, 16));
            //txSecret = MD5( KEY + streamName + txTime )
            $txSecret = md5($this->_play_key_1 . $streamName . $txTime);
            $ext_str = "?" . http_build_query(array(
                "txSecret" => $txSecret,
                "txTime" => $txTime,
            ));
        }

        return [
            "rtmp" => "rtmp://" . $this->_play_domain . "/" . $appName . "/" . $streamName . (isset($ext_str) ? $ext_str : ""),
            "flv" => "https://" . $this->_play_domain . "/" . $appName . "/" . $streamName . ".flv" . (isset($ext_str) ? $ext_str : ""),
            "hls" => "https://" . $this->_play_domain . "/" . $appName . "/" . $streamName . ".m3u8" . (isset($ext_str) ? $ext_str : ""),
            "webrtc" => "webrtc://" . $this->_play_domain . "/" . $appName . "/" . $streamName . (isset($ext_str) ? $ext_str : ""),
        ];
    }

    /**
     *  创建一个直播拉流模板
     *
     * @return array
     */
    public function create_live_pull_from_mp4($fileUrl, $streamName, $StartTime, $EndTime, $Comment, $appName = 'live')
    {
        $req = new CreateLivePullStreamTaskRequest();
        $req->SourceType = "PullVodPushLive";
        $req->SourceUrls = [$fileUrl];
        $req->DomainName = $this->_push_domain;
        $req->AppName = $appName;
        $req->StreamName = $streamName;
        $req->StartTime = gmdate('Y-m-d\TH:i:s\Z', strtotime($StartTime));
        $req->EndTime = gmdate('Y-m-d\TH:i:s\Z', strtotime($EndTime));
        $req->Operator = "test";
        $req->VodLoopTimes = "0";
        //$req->ToUrl = $fileUrl;
        $req->VodLocalMode = 1;
        $req->setComment($Comment);
        //$req->Region = "ap-beijing";
        // $req->ExtraCmd = "ignore_region";
        //  $req -> CallbackUrl
        //$req->setCallbackEvents(["vod_pull_push_event"]);
        $req->setCallbackUrl($this->_callback_url);

        $rep = $this->_liveClient->CreateLivePullStreamTask($req);

        return [
            "id" => $rep->getRequestId(),
            "task_id" => $rep->getTaskId(),
        ];
    }

    public function delete_pull_stream_task($task_id)
    {
        $req = new DeleteLivePullStreamTaskRequest();
        $req->setTaskId($task_id);
        $req->setOperator("administrator");
        $resp = $this->_liveClient->DeleteLivePullStreamTask($req);
        return true;

    }

    public function modify_pull_stream_task($task_id, $fileUrl, $StartTime, $EndTime, $Comment, $Status = "enable")
    {
        $req = new ModifyLivePullStreamTaskRequest();
        $req->setTaskId($task_id);
        $req->setStartTime(gmdate('Y-m-d\TH:i:s\Z', strtotime($StartTime)));
        $req->setEndTime(gmdate('Y-m-d\TH:i:s\Z', strtotime($EndTime)));
        $req->setOperator("administrator");
        $req->SourceUrls = [$fileUrl];
        $req->setComment($Comment);
        $req->setStatus($Status);
        //file_put_contents("./modify_pull_stream_task.txt", $req->serializeToJsonString());

        $resp = $this->_liveClient->ModifyLivePullStreamTask($req);
        return $resp;
    }

    public function stop_pull_stream_task($task_id, $Status = "enable")
    {
        $req = new ModifyLivePullStreamTaskRequest();
        $req->setTaskId($task_id);

        $req->setOperator("administrator");
        $req->setStatus($Status);
        //file_put_contents("./modify_pull_stream_task.txt", $req->serializeToJsonString());

        $resp = $this->_liveClient->ModifyLivePullStreamTask($req);
        return $resp;
    }

    /**
     * Undocumented function
     *
     * @param [type] $task_id
     * @return mixed
     */
    public function get_live_pull_from_mp4_status($task_id)
    {
        $req = new DescribeLivePullStreamTaskStatusRequest();
        $req->TaskId = $task_id;
        $rep = $this->_liveClient->DescribeLivePullStreamTaskStatus($req);
        return $rep->getTaskStatusInfo();
    }

    /**
     * Undocumented function
     *
     * @param [type] $pageNum
     * @param [type] $pageSize
     */
    public function get_all_live_pull_task($pageNum, $pageSize)
    {
        $req = new DescribeLivePullStreamTasksRequest();

        $req->setPageNum($pageNum);
        $req->setPageSize($pageSize);
        $rep = $this->_liveClient->DescribeLivePullStreamTasks($req);
        return $rep;
    }

    public function addRecordTask($streamName, $appName, $StartTime, $EndTime)
    {

        $client = new LiveClient($this->cred, "ap-guangzhou");
        $req = new CreateRecordTaskRequest();
        $req->StreamName = $streamName;
        $req->DomainName = $this->_push_domain;
        $req->AppName = $appName;
        //$req->StartTime = gmdate('Y-m-d\TH:i:s\Z', strtotime($StartTime));
        $req->StartTime = strtotime($StartTime);
        //$req->EndTime = gmdate('Y-m-d\TH:i:s\Z', strtotime($EndTime));
        $req->EndTime = strtotime($EndTime);
        $req->StreamType = 0;
        //$req->setlocale = "ap-guangzhou";
        $req->TemplateId = 1541099;
        $req->Region("ap-beijing");

        $rep = $client->CreateRecordTask($req);

        return [
            "id" => $rep->getRequestId(),
            "record_task_id" => $rep->getTaskId(),
        ];

    }
    public function deleteRecordTask($record_task_id)
    {

        $client = new LiveClient($this->cred, "ap-guangzhou");
        $req = new DeleteRecordTaskRequest();
        $req->setTaskId($record_task_id);
        $resp = $client->DeleteRecordTask($req);
        return true;
    }

    public function listRecordTask($startTime, $endTime, $StreamName = "", $DomainName = "", )
    {

        $client = new LiveClient($this->cred, "ap-guangzhou");
        $req = new DescribeRecordTaskRequest();
        if ($startTime == "") {
            $startTime = strtotime(date("Y-m-d"), time());
            $req->setStartTime($startTime);
        } else {
            $req->setStartTime(strtotime($startTime));
        }

        if ($endTime == "") {
            $endTime = strtotime(date('Y-m-d 23:59:59', time()));
            $req->setEndTime($endTime);
        } else {
            $req->setEndTime(strtotime($endTime));
        }

        $resp = $client->DescribeRecordTask($req);
        return $resp;
    }

}
